package com.yzg.timing;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author misterWei
 * @create 2020年06月14号:18点26分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.ScheduledMain")
public class ScheduledMain {

    public static void main(String[] args) {
        LongAdder longAdder = new LongAdder();
        ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
        log.info("start...");
        /**
         * 次方法的执行规则就是,如果定时执行频率为1秒,但是业务逻辑可能需要执行3秒,那就调度起来就是  3 + 2 秒之后再次调度
         */
        service.scheduleWithFixedDelay(()->{
            longAdder.increment();
            log.info("{}",longAdder.intValue());
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //主线程执行之后过1秒,进行调度执行,调度时间范围为2秒之后
        },1,2,TimeUnit.SECONDS);

    }

    private static void method2() {
        LongAdder longAdder = new LongAdder();
        ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
        log.info("start...");
        /**
         * 次方法的执行规则就是,如果定时执行频率为1秒,但是业务逻辑可能需要执行3秒,那就调度起来就是  3 秒之后再次调度
         */
        service.scheduleAtFixedRate(()->{
             longAdder.increment();
             log.info("{}",longAdder.intValue());
             try {
                 Thread.sleep(3000L);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
          //主线程执行之后过1秒,进行调度执行,调度时间范围为2秒之后
         },1,2, TimeUnit.SECONDS);
    }

    private static void method1() {
        /**
         * 在主线程运行之后过1秒再次执行
         */
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        scheduledExecutorService.schedule(()->{
            log.info("调度执行{}","1");
            //异常不会抛出,内部已经处理;
            int i = 1 /0;
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },1, TimeUnit.SECONDS);

        scheduledExecutorService.schedule(()->{
            log.info("调度执行{}","2");
        },1, TimeUnit.SECONDS);
    }
}
